#include "include.hpp"
// 进程间通信(共享内存加命名管道访问限制)
int main()
{
    // 创建共享内存
    key_t key = ftok(PATH, PRID);
    assert(key != -1);
    int shmid = shmget(key, SIZE, IPC_CREAT | IPC_EXCL | 0666);
    assert(shmid != -1);
    // 创建成功
    cout << shmid << endl;
    cout << "创建临界资源成功" << endl;
    // 开始挂接
    char *address = reinterpret_cast<char *>(shmat(shmid, nullptr, 0));
    // 如果没有挂接成功就打印错误
    if (address == reinterpret_cast<char *>(-1))
        perror("shmat");
    // 挂接成功
    cout << "挂接成功" << endl;
    // 开始使用临界资源
    int n = mkfifo(FIFE_PATH, 0666);
    assert(n != -1);
    // 临界区
    while (true)
    {
        read(0, address + 1, SIZE);
        if (strcmp(address + 1, "quit\n") == 0)
            break;
        run();
    }
    // 删除管道文件
    unlink(FIFE_PATH);
    cout << "管道文件删除成功" << endl;
    // 去除挂接
    int s = shmdt(address);
    assert(s != -1);
    cout << "去除挂接成功" << endl;
    // 释放临界资源
    int ret = shmctl(shmid, IPC_RMID, nullptr);
    assert(ret != -1);
    cout << "释放资源成功" << endl;
    return 0;
}
